package com.apes.framework.plugin.event;


import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;

import java.util.concurrent.Executor;

/**
 * 功能：
 *
 * @author xul
 * @create 2018-02-02 12:00
 */
@Service("apesEventMulticaster")
public class ApesEventMulticaster extends AbstractEventMulticaster {
    protected final Logger logger = LogManager.getLogger(ApesEventMulticaster.class);

    private Executor executor;

    /**
     * Multicast the given application event to appropriate listeners.
     *
     * @param event the event to multicast
     */
    @Override
    public void multicastEvent(final ApesEvent event) {
        try {
            for (final ApesEventListener listener : getApesEventListeners(event)) {
                Executor executor = getExecutor();
                if (!event.isSynchronized() && executor != null) { //异步
                    executor.execute(() -> listener.onEvent(event));
                } else { //同步
                    listener.onEvent(event);
                }
            }
        } catch (Exception e) {
            if (event.isSynchronized()) {
                throw e;
            }
            logger.error("处理" + event.getClass().getName() + "事件发生异常", e);
        }
    }


    public Executor getExecutor() {
        return executor;
    }

    public void setExecutor(Executor executor) {
        this.executor = executor;
    }

}
